package com.xique.gateway.filter;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xique.common.core.constant.CacheConstants;
import com.xique.common.core.constant.Constants;
import com.xique.common.core.constant.UserConstants;
import com.xique.common.core.domain.R;
import com.xique.common.core.utils.ServletUtils;
import com.xique.common.core.utils.StringUtils;
import com.xique.common.redis.service.RedisService;
import com.xique.gateway.config.properties.IgnoreWhiteProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

/**
 * 网关鉴权
 *
 * @author xique
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    private static final Logger log = LoggerFactory.getLogger(AuthFilter.class);

    private static final long EXPIRE_TIME = Constants.TOKEN_EXPIRE * 60;

    private static final long CLIENT_EXPIRE_TIME = Constants.CLIENT_EXPIRE * 60;

    private final static long PARK_MANAGER_EXPIRE_TIME = Constants.TOKEN_EXPIRE * 60 * 2 * 30 * 3;

    private static final long API_EXPIRE_TIME = Constants.API_EXPIRE * 60;

    private final static long PARK_MINI_EXPIRE_TIME = Constants.TOKEN_EXPIRE * 60 * 2 * 30;


    // 排除过滤的 uri 地址，nacos自行添加
    @Autowired
    private IgnoreWhiteProperties ignoreWhite;

    @Resource(name = "stringRedisTemplate")
    private ValueOperations<String, String> sops;

    @Autowired
    private RedisService redisService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String url = exchange.getRequest().getURI().getPath();
//        if (url.contains("client")) {
//            return clientFilter(exchange, chain);
//        }
        String platform = exchange.getRequest().getHeaders().getFirst("platform");
        String projectId = exchange.getRequest().getHeaders().getFirst("projectId");
        if (StringUtils.isNotEmpty(platform) && UserConstants.Platform.API.equals(platform)) {
            // 进入验证
            return apiFilter(exchange, chain);
        }
        if (StringUtils.isNotEmpty(platform) && UserConstants.Platform.API_V1.equals(platform)) {
            // 进入验证
            return apiV1Filter(exchange, chain);
        }
        if (StringUtils.isNotEmpty(platform) && UserConstants.Platform.MINIPROGRAM.equals(platform)) {
            // 进入验证
            return appFilter(exchange, chain);
        }
        if (StringUtils.isNotEmpty(platform) && UserConstants.Platform.PARK_MINIPROGRAM.equals(platform)) {
            // 进入验证
            return parkMiniFilter(exchange, chain);
        }
        // 跳过不需要验证的路径
        if (StringUtils.matches(url, ignoreWhite.getWhites())) {
            return chain.filter(exchange);
        }
        String token = getToken(exchange.getRequest());
        if (StrUtil.isBlank(token)) {
            return setUnauthorizedResponse(exchange, "令牌不能为空");
        }
        token = getTokenKey(token);
        String userStr = sops.get(token);
        if (StringUtils.isNull(userStr)) {
            return setUnauthorizedResponse(exchange, "登录状态已过期");
        }
        JSONObject obj = JSONObject.parseObject(userStr);
        String userid = obj.getString("userId");
        String username = obj.getString("userName");
        String userType = obj.getString("userType");
        String parkId = obj.getString("parkId");
        String clientId = obj.getString("clientId");
        if (StrUtil.isBlank(userid) || StrUtil.isBlank(username)) {
            return setUnauthorizedResponse(exchange, "令牌验证失败");
        }
        if (StringUtils.isEmpty(parkId)) {
            parkId = projectId;
        }

        if (UserConstants.Platform.APP_PARK.equals(platform)) {
            // 设置过期时间
            redisService.expire(token, PARK_MANAGER_EXPIRE_TIME);
        } else {
            // 设置过期时间
            redisService.expire(token, EXPIRE_TIME);
        }

        // 设置用户信息到请求
        ServerHttpRequest mutableReq = exchange.getRequest().mutate().header(CacheConstants.DETAILS_USER_ID, userid)
                .header(CacheConstants.DETAILS_USERNAME, ServletUtils.urlEncode(username))
                .header(CacheConstants.DETAILS_USER_TYPE, userType)
                .header(CacheConstants.DETAILS_PLATFORM_TYPE, platform)
                .header(CacheConstants.DETAILS_PARK_ID, parkId)
                .header(CacheConstants.DETAILS_CLIENT_ID, clientId)
                .build();
        ServerWebExchange mutableExchange = exchange.mutate().request(mutableReq).build();

        return chain.filter(mutableExchange);
    }

    private Mono<Void> clientFilter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String url = exchange.getRequest().getURI().getPath();
        // 跳过不需要验证的路径
        if (StringUtils.matches(url, ignoreWhite.getWhites())) {
            return chain.filter(exchange);
        }
        String token = getToken(exchange.getRequest());
        if (StrUtil.isBlank(token)) {
            return setUnauthorizedResponse(exchange, "令牌不能为空");
        }
        token = getClientTokenKey(token);
        String userStr = sops.get(token);
        if (StringUtils.isNull(userStr)) {
            return setUnauthorizedResponse(exchange, "登录状态已过期");
        }
        JSONObject obj = JSON.parseObject(userStr);
        String userid = obj.getString("userid");
        String username = obj.getString("username");
        String parkId = obj.getString("parkId");
        String clientId = obj.getString("clientId");
        if (StrUtil.isBlank(userid) || StrUtil.isBlank(username)) {
            return setUnauthorizedResponse(exchange, "令牌验证失败");
        }

        // 设置过期时间
        redisService.expire(token, CLIENT_EXPIRE_TIME);
        // 设置用户信息到请求
        ServerHttpRequest mutableReq = exchange.getRequest().mutate().header(CacheConstants.DETAILS_USER_ID, userid)
                .header(CacheConstants.DETAILS_USERNAME, ServletUtils.urlEncode(username))
                .header(CacheConstants.DETAILS_PARK_ID, parkId)
                .header(CacheConstants.DETAILS_CLIENT_ID, clientId).build();
        ServerWebExchange mutableExchange = exchange.mutate().request(mutableReq).build();

        return chain.filter(mutableExchange);
    }

    private Mono<Void> apiFilter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String url = exchange.getRequest().getURI().getPath();
        // 跳过不需要验证的路径
        if (StringUtils.matches(url, ignoreWhite.getWhites())) {
            return chain.filter(exchange);
        }
        String token = getToken(exchange.getRequest());
        if (StrUtil.isBlank(token)) {
            return setUnauthorizedResponse(exchange, "令牌不能为空");
        }
        token = getApiTokenKey(token);
        String userStr = sops.get(token);
        if (StringUtils.isNull(userStr)) {
            return setUnauthorizedResponse(exchange, "登录状态已过期");
        }
        JSONObject obj = JSON.parseObject(userStr);
        String userId = obj.getString("userId");
        String userName = obj.getString("userName");
        String parkId = obj.getString("parkId");
        if (StrUtil.isBlank(userId) || StrUtil.isBlank(userName)) {
            return setUnauthorizedResponse(exchange, "令牌验证失败");
        }

        // 设置过期时间
        redisService.expire(token, API_EXPIRE_TIME);
        // 设置用户信息到请求
        ServerHttpRequest mutableReq = exchange.getRequest().mutate().header(CacheConstants.DETAILS_USER_ID, userId)
                .header(CacheConstants.DETAILS_USERNAME, ServletUtils.urlEncode(userName))
                .header(CacheConstants.DETAILS_PARK_ID, parkId).build();
        ServerWebExchange mutableExchange = exchange.mutate().request(mutableReq).build();

        return chain.filter(mutableExchange);
    }

    private Mono<Void> apiV1Filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String url = exchange.getRequest().getURI().getPath();
        // 跳过不需要验证的路径
        if (StringUtils.matches(url, ignoreWhite.getWhites())) {
            return chain.filter(exchange);
        }
        String token = getToken(exchange.getRequest());
        if (StrUtil.isBlank(token)) {
            return setUnauthorizedResponse(exchange, "令牌不能为空");
        }
        token = getApiV1TokenKey(token);
        String userStr = sops.get(token);
        if (StringUtils.isNull(userStr)) {
            return setUnauthorizedResponse(exchange, "登录状态已过期");
        }
        JSONObject obj = JSON.parseObject(userStr);
        String appId = obj.getString("appId");
        String foreignId = obj.getString("foreignId");
        String foreignName = obj.getString("foreignName");
        String foreignType = obj.getString("foreignType");
        String whiteUrl = obj.getString("whiteUrl");
        if (StrUtil.isBlank(appId)) {
            return setUnauthorizedResponse(exchange, "令牌验证失败");
        }
        if (StrUtil.isBlank(whiteUrl)) {
            return setUnauthorizedResponse(exchange, "无接口访问权限");
        } else {
            String[] whiteUrlArray = whiteUrl.split(",");
            if (!ArrayUtil.contains(whiteUrlArray, url)) {
                return setUnauthorizedResponse(exchange, "无接口访问权限");
            }
        }

        // 设置用户信息到请求
        ServerHttpRequest mutableReq = exchange.getRequest().mutate().header(CacheConstants.APP_ID, appId)
                .header(CacheConstants.FOREIGN_NAME, ServletUtils.urlEncode(foreignName == null ? "" : foreignName))
                .header(CacheConstants.FOREIGN_TYPE, ServletUtils.urlEncode(foreignType))
                .header(CacheConstants.FOREIGN_ID, foreignId)
                .build();
        ServerWebExchange mutableExchange = exchange.mutate().request(mutableReq).build();

        return chain.filter(mutableExchange);
    }

    private Mono<Void> appFilter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String url = exchange.getRequest().getURI().getPath();
        // 跳过不需要验证的路径
        if (StringUtils.matches(url, ignoreWhite.getWhites())) {
            return chain.filter(exchange);
        }
        String token = getToken(exchange.getRequest());
        if (StrUtil.isBlank(token)) {
            return setUnauthorizedResponse(exchange, "令牌不能为空");
        }
        token = getAppTokenKey(token);
        String userStr = sops.get(token);
        if (StringUtils.isNull(userStr)) {
            return setUnauthorizedResponse(exchange, "登录状态已过期");
        }
        JSONObject obj = JSON.parseObject(userStr);
        String baseUserId = obj.getString("baseUserId");
        String userId = obj.getString("userId");
        String userName = obj.getString("userName");
        String parkId = obj.getString("parkId");
        if (StrUtil.isBlank(baseUserId) || StrUtil.isBlank(userName)) {
            return setUnauthorizedResponse(exchange, "令牌验证失败");
        }

        // 设置用户信息到请求
        ServerHttpRequest mutableReq = exchange.getRequest().mutate()
                .header(CacheConstants.DETAILS_BASE_USER_ID, baseUserId)
                .header(CacheConstants.DETAILS_USER_ID, userId)
                .header(CacheConstants.DETAILS_USERNAME, ServletUtils.urlEncode(userName))
                .header(CacheConstants.DETAILS_PARK_ID, parkId)
                .build();
        ServerWebExchange mutableExchange = exchange.mutate().request(mutableReq).build();

        return chain.filter(mutableExchange);
    }

    private Mono<Void> parkMiniFilter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String url = exchange.getRequest().getURI().getPath();
        // 跳过不需要验证的路径
        if (StringUtils.matches(url, ignoreWhite.getWhites()))
        {
            return chain.filter(exchange);
        }
        String token = getToken(exchange.getRequest());
        if (StringUtils.isBlank(token))
        {
            return setUnauthorizedResponse(exchange, "令牌不能为空");
        }
        token = getParkMiniTokenKey(token);
        String userStr = sops.get(token);
        if (StringUtils.isNull(userStr))
        {
            return setUnauthorizedResponse(exchange, "登录状态已过期");
        }
        JSONObject obj = JSONObject.parseObject(userStr);
        String openId = obj.getString("openId");
        String unionId = obj.getString("unionId");
        String baseUserId = obj.getString("baseUserId");
        String zfbUserId = obj.getString("zfbUserId");
        String userName = obj.getString("userName");
        String parkId = obj.getString("parkId");
        String appType = obj.getString("appType");
        if (StringUtils.isBlank(baseUserId) || StringUtils.isBlank(userName))
        {
            return setUnauthorizedResponse(exchange, "令牌验证失败");
        }

        // 设置过期时间
        redisService.expire(token, PARK_MINI_EXPIRE_TIME);

        // 设置用户信息到请求
        ServerHttpRequest mutableReq = exchange.getRequest().mutate()
                .header(CacheConstants.DETAILS_BASE_USER_ID, baseUserId)
                .header(CacheConstants.ZFB_USER_ID, zfbUserId)
                .header(CacheConstants.DETAILS_USERNAME, ServletUtils.urlEncode(userName))
                .header(CacheConstants.DETAILS_PARK_ID, parkId)
                .header(CacheConstants.OPEN_ID, openId)
                .header(CacheConstants.UNION_ID, unionId)
                .header(CacheConstants.APP_TYPE, appType)
                .build();
        ServerWebExchange mutableExchange = exchange.mutate().request(mutableReq).build();

        return chain.filter(mutableExchange);
    }

    private Mono<Void> setUnauthorizedResponse(ServerWebExchange exchange, String msg)
    {
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        response.setStatusCode(HttpStatus.OK);

        log.error("[鉴权异常处理]请求路径:{},{}", exchange.getRequest().getPath(), msg);

        return response.writeWith(Mono.fromSupplier(() -> {
            DataBufferFactory bufferFactory = response.bufferFactory();
            return bufferFactory.wrap(JSON.toJSONBytes(R.fail(HttpStatus.UNAUTHORIZED.value(), msg)));
        }));
    }

    private String getClientTokenKey(String token) {
        return "gt_" + CacheConstants.LOGIN_TOKEN_KEY + token;
    }

    private String getApiTokenKey(String token) {
        return "api_" + CacheConstants.LOGIN_TOKEN_KEY + token;
    }

    private String getApiV1TokenKey(String token) {
        return "access_token_api_" + CacheConstants.LOGIN_TOKEN_KEY + token;
    }

    private String getAppTokenKey(String token) {
        return "app_" + CacheConstants.LOGIN_TOKEN_KEY + token;
    }

    private String getParkMiniTokenKey(String token)
    {
        return "park_mini_" + CacheConstants.LOGIN_TOKEN_KEY + token;
    }

    private String getTokenKey(String token)
    {
        return CacheConstants.LOGIN_TOKEN_KEY + token;
    }

    /**
     * 获取请求token
     */
    private String getToken(ServerHttpRequest request) {
        String token = request.getHeaders().getFirst(CacheConstants.HEADER);
        if (StringUtils.isNotEmpty(token) && token.startsWith(CacheConstants.TOKEN_PREFIX)) {
            token = token.replace(CacheConstants.TOKEN_PREFIX, "");
        }
        return token;
    }

    @Override
    public int getOrder() {
        return -200;
    }
}
